package cn.bx.bid.ctrl;

import cn.bx.bid.entity.Page;
import cn.bx.bid.entity.User;
import cn.bx.bid.service.UserService;
import cn.bx.bid.util.LogUtil;
import cn.bx.bid.util.StringUtil;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Api("管理员操作接口")
@RestController
public class UserController {

    @Autowired
    private UserService userService;

    @ApiOperation("管理员登录")
    //@ApiParam(name = "username",required = true,value="用户名")
   // @ApiParam(name = "password",required = true,value="用户密码")

    @PostMapping(value = "ulogin", produces = "application/json;charset=utf-8")
    public Rtn ulogin(String username, String password, HttpSession s)
            throws ServletException, IOException {

        User u = this.userService.login(username, password);
        if (u != null)
            s.setAttribute("USER_LOGIN", u);
//        java.util.Map<String,Object> rtn=new HashMap<>();
//        rtn.put("msg",u!=null);
//        rtn.put("obj",u);

        return Rtn.getRtn(u != null, u);
    }

    @ApiOperation("管理员查询")
    @GetMapping(value = "userSearch", produces = "application/json;charset=utf-8")
    public Page<User> userSearch(@RequestParam(name = "page", defaultValue = "1") int pageNo, @RequestParam(name = "limit", defaultValue = "10") int limit, @RequestParam(name = "name", required = false) String name, @RequestParam(name = "start", required = false) Date start, @RequestParam(name = "end", required = false) Date end) {

        Page<User> page = userService.paging(pageNo, limit, name, start, end);
        return page;
    }

    @ApiOperation("管理员添加")
    @PostMapping(value = "userAdd", produces = "application/json;charset=utf-8")
    public Rtn userAdd(@ModelAttribute("u") User u) {

        int r = userService.add(u);
        return Rtn.getRtn(r > 0, null);
    }

    @RequestMapping(value = "batchDel", produces = "application/json;charset=utf-8")
    public Rtn batchDel(@RequestParam("ids[]") long[] ids) {
        // Log.info(">>>>>>>>>>>>>>>>>>>>");
        //long ar[] = request.getParameterValues("ids[]");//特别注意，后面要加[]符号
        //用逗号分隔
        int r = userService.batchDel(ids);
        return Rtn.getRtn(r > 0, null);

    }
    //验证用户名是否重复
    @RequestMapping(value = "checkUserNameRepeat", produces = "application/json;charset=utf-8")

    public Rtn checkUserNameRepeat(@RequestParam("userName") String name,@RequestParam(name="id",required = false) Long id) {

        boolean repeat = this.userService.checkUserNameRepeat(id, name);

        return Rtn.getRtn(repeat,null);
    }

//    @PostMapping("login")
//    public String login(
//            HttpServletRequest request,
//            @RequestParam("username") String n,
//            @RequestParam(name = "pass", required = true) String p) {
//        //request.setCharacterEncoding("utf-8");
//        User user = userService.login(n, p);
//
//        // if (n.startsWith("java63") && p.equals("123456")) {
//        if (user != null) {
//            request.getSession().setAttribute("USER_LOGIN", user);
//            //return "welcome.jsp";
//            return "forward:/welcome.jsp";
//        }
//        request.setAttribute("msg", "错误的用户名或者密码！@");
//        return "forward:/fail.jsp";
//    }
//
//    //不太推荐
////    public String test(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
////        //req.getSession().getServletContext();
////        //ContextLoaderListener;
////
////        req.getRequestDispatcher("/welcome.jsp").forward(req,resp);
////        return null;
////    }
//
//    @GetMapping("toUserAdd")
//    public String toAdd() {
//        return "useradd";
//    }
//
//    //新管理员注册
//    @RequestMapping("adminRegister")
//    public String register(@ModelAttribute("u") User user) {
////        CharacterEncodingFilter f=null;
////        f.setForceEncoding(true);
////        f.setEncoding("utf-8");
//        LogUtil.debug("新管理员：" + user + "保存成功了");
//        int r = this.userService.add(user);
//
//        //return "registerOk.jsp";
//        //return "/WEB-INF/pages/registerOk.jsp";
//        //return "registerOk";
//        return "redirect:usersearch.jhtml";
//    }
//
//    @GetMapping("usersearch")
//    public ModelAndView search(@RequestParam(name = "page", defaultValue = "1") int pageNo, @RequestParam(name = "limit", defaultValue = "10") int limit, @RequestParam(name = "name", required = false) String name, @RequestParam(name = "startDate", required = false) Date start, @RequestParam(name = "endDate", required = false) Date end) {
//        ModelAndView mv = new ModelAndView();
//        Page<User> page = this.userService.paging(pageNo, limit, name, start, end);
//        mv.addObject("p", page);
//        mv.setViewName("adminlist");
//        return mv;
////        //HttpServletRequest request,
////        List<User> users = new ArrayList<>();
////        for (int i = 1; i <= 10; i++) {
////            users.add(new User(i * 10L, 1L, "liu" + i, "111" + i, "111" + i, "11111" + i, "2222" + i, null, null));
////        }
////        ModelAndView mv = new ModelAndView();
////        //mv.setViewName("userlist.jsp");
////        mv.setViewName("userlist");
////        mv.addObject("users", users);
////        return mv;
//    }
////    public String login(HttpServletRequest request){
////        String name=request.getParameter("")
////        return "";
////    }
//    @GetMapping("toUser-update-{id}")
//    public String toUpdate(@PathVariable("id") long id, Model m){
//        User u=this.userService.get(id);
//        m.addAttribute("user",u);//也可以带对象给视图
//        return "userupdate";
//    }

    @InitBinder//从请求到Controller
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
        // true:允许输入空值，false:不能为空值
    }
    //这个方法处理所有的UserController产生的异常
    @ExceptionHandler
    public String exceptionHandler(Exception e){
        LogUtil.error("出现异常",e);
        return "error";
    }
}